/*
 * This file is part of Cadmium.
 * Copyright (C) 2007-2010 Xavier Clerc.
 *
 * Cadmium is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * Cadmium is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package fr.x9c.cadmium.primitives.num;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;

import fr.x9c.cadmium.kernel.Block;
import fr.x9c.cadmium.kernel.Custom;
import fr.x9c.cadmium.kernel.Fatal;
import fr.x9c.cadmium.kernel.Value;
import fr.x9c.cadmium.util.IO;
import fr.x9c.cadmium.util.Misc;

/**
 * This class defines operations for custom type "_nat".
 *
 * @author <a href="mailto:cadmium@x9c.fr">Xavier Clerc</a>
 * @version 1.0
 * @since 1.0
 */
final class CustomNat extends Custom.AbstractOperations {

    /** Custom operations for "_nat". */
    static final Custom.Operations OPS = new CustomNat();

    /**
     * Only one instance of this class.
     */
    private CustomNat() {
        super("_nat", false, false, true);
    } // end empty constructor

    /**
     * {@inheritDoc}
     */
    @Override
    public Custom.SerializationSizes serialize(final DataOutput out,
                                               final Value v)
        throws IOException {
        final int[] b = (int[]) v.asBlock().asCustom();
        final int len = b.length;
        IO.write32u(out, len);
        for (int i = 0; i < len; i++) {
            IO.write32s(out, b[i]);
        } // end for
        return new Custom.SerializationSizes(len * Nat.DIGIT_SIZE_IN_BYTES,
                                             len * Nat.DIGIT_SIZE_IN_BYTES);
    } // end method 'serialize(DataOutput, Value)'

    /**
     * {@inheritDoc}
     */
    @Override
    public long deserialize(final DataInput in, final Block dst)
        throws IOException, Fatal.Exception {
        final int len = Misc.ensure32s(IO.read32u(in));
        final int[] b = new int[len];
        for (int i = 0; i < len; i++) {
            b[i] = IO.read32s(in);
        } // end for
        dst.setCustom(b);
        return len * Nat.DIGIT_SIZE_IN_BYTES;
    } // end method 'deserialize(DataInput, Block)'

} // end class 'CustomNat'
